package com.warmheart.core.combine.oper;

import java.util.Iterator;
import java.util.List;

import com.warmheart.core.co.builder.CoBuilder;
import com.warmheart.core.co.enums.OrderTypeEnum;
import com.warmheart.core.co.model.OrderByModel;
import com.warmheart.core.co.oper.Co;
import com.warmheart.core.constant.Globals;
import com.warmheart.core.cors.builder.CoRsBuilder;

/**
 * 
 * @ClassName: Order
 * @Description: 该类用作对联合查询排序进行处理
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 * @param <P>
 * @param <PE>
 */
public class Order<P extends CoRsBuilder<PE, ?>, PE extends CoBuilder<P>> {

    private final Combine combine;

    private final Co<P, PE> pCo;

    public Order(Combine combine, Co<P, PE> pCo) {
        this.combine = combine;
        this.pCo = pCo;
    }

    public Combine asc() {
        String pAlias = this.combine.aliasName(this.pCo.core());
        List<OrderByModel> orderList = this.combine.mainT().getJoinModel().getOrderList();
        Iterator<OrderByModel> iterator = orderList.iterator();
        while (iterator.hasNext()) {
            OrderByModel element = iterator.next();
            if ((pAlias + Globals.DOT + this.pCo.fetchField()).equals(element.getOrderByField())) {
                iterator.remove();
                // 排序只可能有一个，可以直接中断循环
                break;
            }
        }
        orderList.add(new OrderByModel(pAlias + Globals.DOT + this.pCo.fetchField(), OrderTypeEnum.ASC));
        return this.combine;
    }

    public Combine desc() {
        String pAlias = this.combine.aliasName(this.pCo.core());
        List<OrderByModel> orderList = this.combine.mainT().getJoinModel().getOrderList();
        Iterator<OrderByModel> iterator = orderList.iterator();
        while (iterator.hasNext()) {
            OrderByModel element = iterator.next();
            if ((pAlias + Globals.DOT + this.pCo.fetchField()).equals(element.getOrderByField())) {
                iterator.remove();
                // 排序只可能有一个，可以直接中断循环
                break;
            }
        }
        orderList.add(new OrderByModel(pAlias + Globals.DOT + this.pCo.fetchField(), OrderTypeEnum.DESC));
        return this.combine;
    }

    public void clear() {
        String pAlias = this.combine.aliasName(this.pCo.core());
        List<OrderByModel> orderList = this.combine.mainT().getJoinModel().getOrderList();
        Iterator<OrderByModel> orderIterator = orderList.iterator();
        while (orderIterator.hasNext()) {
            OrderByModel element = orderIterator.next();
            if ((pAlias + Globals.DOT + this.pCo.fetchField()).equals(element.getOrderByField())) {
                orderIterator.remove();
            }
        }
    }

    public Combine combine() {
        return this.combine;
    }
}
